package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.compiler.ast.Variable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.sql.Time;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Slf4j
@Component
public class RedisIdWorker {
    private static long BEGIN_TIMESTAMP = 1704070800L;
    private static final int COUNT_BITS = 32;
    private final StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefid){
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSeond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSeond-BEGIN_TIMESTAMP;

        //生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:"+keyPrefid + ":" + date,1);
        //生成序列号拼接并返回
        return timeStamp << COUNT_BITS | count;
    }


}
